package com.tensquare.base.service;

import com.tensquare.base.dao.LabelRepository;
import com.tensquare.base.po.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import utils.IdWorker;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class LabelService {

    @Autowired
    private LabelRepository labelRepository;
    @Autowired
    private IdWorker idWorker;


    /*
    * 根据条件查询列表
    * */
    public Specification<Label> getLabelSpecification(Map<String,Object> searchMap){
        Specification<Label> spec = (root,query,cb)->{
            List<Predicate>  andPredicateList = new ArrayList<>();

            //标签名称
            if(!StringUtils.isEmpty(searchMap.get("labelname"))){
                andPredicateList.add(
                        cb.like(root.get("labelname").as(String.class),"%"+searchMap.get("labelname")+"%")
                );
            }

            //状态
            if(!StringUtils.isEmpty(searchMap.get("state"))){
                andPredicateList.add(
                        cb.equal(root.get("state").as(String.class),searchMap.get("state"))
                );
            }

            if(!StringUtils.isEmpty(searchMap.get("recommed"))){
                andPredicateList.add(
                        cb.equal(root.get("recommend").as(String.class),searchMap.get("recommend"))
                );
            }
            return cb.and(andPredicateList.toArray(new Predicate[andPredicateList.size()]));
        };
        return spec;
    }

    public Page<Label> page(Map<String,Object> searchMap, int page, int size){
        Specification<Label> labelList = getLabelSpecification(searchMap);

        Pageable of = PageRequest.of(page-1, size);
        return labelRepository.findAll(labelList,of);
    }

    /*
    * 保存一个标签
    * */
    public void saveLabel(Label label){
        //设置ID
        label.setId(idWorker.nextId()+"");
        labelRepository.save(label);
    }

    /*
    * 更新一个标签
    * */
    public void updateLabel(Label label){
        labelRepository.save(label);
    }

    /*
    * 删除一个标签
    * */
    public void deleteLabelById(String id){
        labelRepository.deleteById(id);
    }

    /*
    * 查询全部标签
    * */
    public List<Label> findLabelList(){
        return labelRepository.findAll();
    }

    /*
    * 根据id查询标签
    * */
    public Label findLabelById(String id){
        return labelRepository.findById(id).get();
    }



















}
